<template>
  <!-- 底部回复组件 -->
  <div>
    <div class="footer">
      <div class="footer-item">
        <a title="点赞数" @click="updatelike">
          <i class="iconfont icon-dianzan"></i>
          &nbsp;{{item.like_count}}
        </a>
      </div>
      <div class="footer-item">
        <a title="回复作者" @click="unflod">
          <i class="iconfont icon-huifu1"></i>&nbsp;回复
        </a>
      </div>
      <div class="footer-item">
        <a title="加入喜欢" @click="joinlike">
          <i class="iconfont icon-shoucang"></i>&nbsp;喜欢
        </a>
      </div>
      <div class="footer-item">
        <a title="举报作者" @click="dialogReport = true">
          <i class="iconfont icon-jubao"></i>&nbsp;举报
        </a>
      </div>
    </div>
    <!-- 评论区展开区域 -->
    <div class="unflod" v-if="isActive">
      <!-- 发布评论 -->
      <div class="publish">
        <textarea rows="1" cols="70" placeholder="快来发送评论吧" v-model="message"></textarea>
        <div class="publish-btn">
          <h5>
            <span class="num">{{msg}}</span>&nbsp;/30
          </h5>
          <button class="btn" @click="handlecomment">评论</button>
        </div>
      </div>
      <div class="line"></div>
      <div class="sort">
        <div :class="[screen==='hint'?'active':'','sort-item']" @click="cutscreen('hint')">热度</div>
        <div :class="[screen==='time'?'active':'','sort-item']" @click="cutscreen('time')">时间</div>
      </div>
      <!-- 评论区 -->
      <div class="content" v-if="commentArr.length !== 0">
        <div class="content-item" v-for="item in commentArr" :key="item.id">
          <!-- 头像 -->
          <div class="headimg" v-if="item.user_pic">
            <img :src="item.user_pic" />
          </div>
          <div class="headimg_div" v-else>匿名</div>
          <div class="nickname">
            <h4>
              {{item.nickname?item.nickname:'匿名'}}&nbsp;:&nbsp;
              <span
                class="message"
              >{{item.message}}</span>
              <a title="回复评论" class="click" @click="reply(item)">
                <i class="iconfont icon-dianzan"></i>&nbsp;回复
              </a>
              <a title="举报评论" class="click" @click="commentReport(item)">
                <i class="iconfont icon-jubao"></i>&nbsp;举报
              </a>
            </h4>
            <div class="timer">{{timer(item.timer)}}</div>
            <!-- 预展开二级回复 -->
            <div
              class="reply_item"
              v-if="item.reply_count > 0 && item.isreply"
              @click="secondReply(item)"
            >-----可展开{{item.reply_count}}条回复-----</div>
            <!-- 二级评论区 -->
            <div class="content" v-if="item.reply_count > 0 && !item.isreply">
              <!-- 当请求值还没获取到时 -->
              <div v-if="item.children">
                <div class="content-item" v-for="subitem in item.children" :key="subitem.id">
                  <!-- 二级头像 -->
                  <div class="headimg" v-if="subitem.user_pic">
                    <img :src="subitem.user_pic" />
                  </div>
                  <div class="headimg_div" v-else>匿名</div>
                  <!-- 二级信息 -->
                  <div class="nickname">
                    <h4>
                      {{subitem.nickname?subitem.nickname:'匿名'}}&nbsp;回复&nbsp;{{subitem.sup_nickname?subitem.sup_nickname:'匿名'}}&nbsp;:&nbsp;
                      <span
                        class="message"
                      >{{subitem.message}}</span>
                      <a title="回复评论" class="click" @click="reply(subitem)">
                        <i class="iconfont icon-dianzan"></i>&nbsp;回复
                      </a>
                      <a title="举报评论" class="click" @click="commentReport(subitem)">
                        <i class="iconfont icon-jubao"></i>&nbsp;举报
                      </a>
                    </h4>
                    <div class="timer">{{timer(subitem.timer)}}</div>
                  </div>
                </div>
              </div>
              <!-- 则展示 -->
              <div v-else>努力加载中</div>
            </div>
          </div>
        </div>
      </div>
      <div class="hint" v-else>暂时还没评论，抢沙发！</div>
      <!-- 查看更多评论 -->
      <div class="more" v-show="isShow" @click="readmore">查看更多 >></div>
    </div>
    <!-- 回复对话框 -->
    <el-dialog
      title="回复"
      :visible.sync="centerDialogVisible"
      width="50%"
      :before-close="beforeclose"
    >
      <div class="publish">
        <h4 class="dialog_title">
          回复该评论&nbsp;&nbsp;
          {{byreplyinfo.nickname?byreplyinfo.nickname:'匿名'}}&nbsp;:&nbsp;
          <span
            class="message"
          >{{byreplyinfo.message}}</span>
        </h4>
        <textarea rows="1" cols="70" placeholder="要回复什么呢" v-model="replymessage"></textarea>
        <div class="publish-btn">
          <h5>
            <span class="num">{{replymsg}}</span>&nbsp;/30
          </h5>
          <button class="btn" @click="handlereply">回复</button>
        </div>
      </div>
    </el-dialog>
    <!-- 这是举报对话框，如果是不为true，也没必要加载 -->
    <Report v-if="dialogReport" :dialogReport="dialogReport" :walls="item" @clickClose="getClose"></Report>
    <!-- 评论举报对话框 -->
    <el-dialog title="举报评论信息填写" :visible.sync="commentreport" width="50%" :show-close="false">
      <div class="comment_report">
        <div class="headimg" v-if="com_reportInfo.user_pic">
          <img :src="com_reportInfo.user_pic" alt="头像" />
        </div>
        <div class="headimg_div" v-else>匿名</div>
        <div>
          昵称: {{com_reportInfo.nickname?com_reportInfo.nickname:'匿名'}}
          <div class="message">
            <p>评论内容: {{com_reportInfo.message}}</p>
          </div>
        </div>
      </div>
      <div class="publish">
        <textarea rows="4" cols="70" placeholder="请详细说明违规用户的违规区域(昵称，发布评论内容，头像)" v-model="expound"></textarea>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentreport = false">取消举报</el-button>
        <el-button type="primary" @click="subReport">提交举报</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
// 引入子组件
import Report from "./report/index.vue";
export default {
  props: ["item"],
  data() {
    return {
      isActive: false, // 控制评论区的展开
      message: "", //评论内容
      replymessage: "", //回复内容
      commentArr: [], //评论区数据
      isShow: true, //显示底部加载更多区域
      centerDialogVisible: false, //控制对话框的显示与隐藏
      firstreplyinfo: {}, //一级回复者的信息
      byreplyinfo: {}, //多级被回复者的信息
      isreply: true, //控制二级回复的显示
      screen: "hint", //控制筛选的切换
      hintcount: 0, //热度起始值
      timecount: 0, //时间起始值
      islike: true, //节流控制
      dialogReport: false, //控制举报文章对话框的显示与隐藏
      commentreport: false, //控制举报评论对话框的显示与隐藏
      expound: "", //举报评论的阐述
      com_reportInfo: {}, //被举报评论信息
    };
  },
  methods: {
    // 展开评论区的回调（获取一级评论信息）
    async unflod() {
      // 展开
      this.isActive = !this.isActive;
      // 判断isActive为true则是打开，需要获取数据，反之关闭不需要
      if (this.isActive) {
        // 获取评论区数据 默认获取热度
        let result = await this.$API.getcommentByhint(
          this.item.id,
          this.hintcount
        );
        this.getCommentData(result);
      } else {
        //关闭评论区时 复原原始值
        Object.assign(this.$data, this.$options.data());
      }
    },
    // 整理评论数据结果回调
    getCommentData(result) {
      if (result.code === 200) {
        // 可以在这里判断返回的数据是否达到了五条
        if (result.data.length !== 5) {
          this.isShow = false;
        } else {
          this.isShow = true;
        }
        // 为了控制每一个二级评论，是每个评论区都是独立的，需要我们循环添加一个isreply字段
        result.data.forEach((item) => {
          item.isreply = true;
          this.commentArr.push(item);
        });
      }
    },
    // 发布评论回调
    handlecomment() {
      let data = {};
      // 判断用户内容是否为空
      if (this.message.length <= 0) {
        return this.$message({
          type: "error",
          message: "评论内容不能为空",
        });
      }
      data.ranks = 1; //发布者层级，1级为发布者2级为回复者
      data.message = this.message; //内容字段
      // 发布评论功能函数
      this.publishcomment(data);
    },
    // 打开对话框回调
    reply(item) {
      this.centerDialogVisible = true;
      this.byreplyinfo = item; //把要回复的信息赋值
    },
    // 关闭对话框的回调
    beforeclose(done) {
      this.replymessage = "";
      done();
    },
    // 回复回调
    handlereply() {
      let data = {};
      // 判断用户内容是否为空
      if (this.replymessage.length <= 0) {
        return this.$message({
          type: "error",
          message: "回复内容不能为空",
        });
      }
      data.ranks = 2; //发布者层级，1级为发布者2级为回复者
      data.message = this.replymessage; //内容字段
      data.superiorId = this.byreplyinfo.id; //上一级id（被回复者）
      // 判断 如果你回复的是一级评论，我们的firstreplyinfo还没数据
      if (this.firstreplyinfo.id) {
        data.tallest_id = this.firstreplyinfo.id; //上一级的一层id
      } else {
        data.tallest_id = this.byreplyinfo.id; //上一级的一层id
      }
      data.sup_nickname = this.byreplyinfo.nickname; //上一级昵称
      // 发布评论功能函数
      this.publishcomment(data);
      this.centerDialogVisible = false; //关闭对话框
    },
    // 发布评论回调
    async publishcomment(comments) {
      // 整理参数 需要walls_id timer user_pic nickname uuId
      let data = { ...comments }; //声明一个对象，储存将要发送给服务器的值
      data.walls_id = this.item.id; //这篇文章的id
      data.timer = dayjs().format("YYYY-MM-DD HH:mm:ss"); //获取现在时间
      let { uuId, nickname, user_pic } = this.userinfo; //自己的信息
      Object.assign(data, {
        uuId,
        nickname,
        user_pic,
      });
      // 发送请求;
      let result = await this.$API.publishcomment(data);
      if (result.code === 200) {
        this.$message({
          type: "success",
          message: result.message,
        });
        // 插入到评论区数组最前面 要判断层级添加到不同的地方
        if (data.ranks === 1) {
          this.commentArr.unshift(data);
          // 清空输入框内容 加异步是因为会在插入数据之前删除message字段
          this.message = "";
        } else if (data.ranks === 2) {
          // 重新获取二级评论区的数据来刷新页面
          // 因为我们需要一个对象
          let item = { id: data.tallest_id };
          this.secondReply(item);
          this.replymessage = "";
        }
      }
    },
    // 获取二级回复的数据
    async secondReply(iteminfo) {
      this.firstreplyinfo = iteminfo; //把一级评论信息赋值
      // 显示二级回复
      iteminfo.isreply = false;
      // 发起请求 参数是一级的id
      let result = await this.$API.getreplyByid(iteminfo.id);
      if (result.code === 200) {
        // 我们应该把数据放到了相应的一级评论数组中 不能直接赋值给一个数组，这样会使数组单一
        this.commentArr.forEach((item) => {
          if (item.id === iteminfo.id) {
            // 添加响应式的值
            this.$set(item, "children", result.data);
          }
        });
      }
    },
    // 切换筛选回调
    async cutscreen(screen) {
      this.screen = screen; //把最新的筛选赋值
      // 在切换的时候应该把我们储存的一级信息和被回复者信息删除
      this.firstreplyinfo = {};
      this.byreplyinfo = {};
      this.commentArr = [];
      // 判断 通过什么字段筛选
      if (screen === "hint") {
        this.hintcount = 0;
        let result = await this.$API.getcommentByhint(
          this.item.id,
          this.hintcount
        );
        this.getCommentData(result);
        // 通过热度排序获取值
      } else if (screen === "time") {
        this.timecount = 0;
        // 通过时间排序获取值
        let result = await this.$API.getcommentByid(
          this.item.id,
          this.timecount
        );
        this.getCommentData(result);
      }
    },
    // 查看更多的回调
    async readmore() {
      // 判断在时间筛选还是热度筛选
      if (this.screen === "hint") {
        this.hintcount += 5;
        let result = await this.$API.getcommentByhint(
          this.item.id,
          this.hintcount
        );
        this.getCommentData(result);
      } else if (this.screen === "time") {
        this.timecount += 5;
        // 发起请求
        let result = await this.$API.getcommentByid(
          this.item.id,
          this.timecount
        );
        this.getCommentData(result);
      }
    },
    // 修改点赞的回调
    async updatelike() {
      // 判断是否登录
      let isLogin = localStorage.getItem("WALLTOKEN");
      // 需要一个对象，有文章id和用户id
      let data = {};
      data.walls_id = this.item.id;
      data.uuId = this.userinfo.uuId;
      if (isLogin) {
        // 节流
        if (this.islike) {
          let result = await this.$API.updatelike(data);
          this.islike = false;
          if (result.code === 200) {
            // 判断是点赞还是取消点赞
            if (result.data.islike) {
              //注意 +会当作成字符串拼接
              this.item.like_count = this.item.like_count * 1 + 1;
            } else {
              this.item.like_count -= 1;
            }
            this.$message({
              type: "success",
              message: result.message,
            });
          }
          setTimeout(() => {
            this.islike = true;
          }, 2000);
        }
      }
    },
    // 子组件传入关闭对话框的回调
    getClose() {
      this.dialogReport = false;
    },
    // 打开举报评论的回调
    commentReport(item) {
      this.com_reportInfo = item;
      this.commentreport = true;
      console.log(this.com_reportInfo, "数据");
    },
    // 提交评论举报回调
    subReport() {
      if (this.expound.trim() === "") {
        return this.$message({
          type: "error",
          message: "举报阐述不能为空哦",
        });
      }
      // 整理参数 需要参数有wall_id,nickname,message,user_pic
      let { nickname, message, user_pic } = this.com_reportInfo;
      let data = {};
      Object.assign(data, { nickname, message, user_pic });
      data.walls_id = this.com_reportInfo.id; //该条评论的id
      data.author_id = this.com_reportInfo.uuId; //评论者id
      data.expound = this.expound; //举报者阐述信息
      data.types = 1; //评论举报类型为1
      // 发送提交信息请求
      this.reportwalls(data);
    },
    // 发起举报请求的回调
    async reportwalls(data) {
      let result = await this.$API.reportwalls(data);
      if (result.code === 200) {
        this.$message({
          type: "success",
          message: result.message,
        });
        // 关闭对话框
        this.commentreport = false;
        this.expound = ""; //清空用户阐述
      } else {
        this.$message({
          type: "error",
          message: result.message,
        });
      }
    },
    // 加入喜欢回调
    async joinlike() {
      // 整理参数 解构出需要的值
      let {
        nickname,
        user_pic,
        from,
        message,
        uuId,
        cha_types,
        def_type,
        like_count,
      } = this.item;
      let data = {};
      data.pic_walls = ""; //照片墙
      // 要将timer字段转换成数据库识别的格式
      data.timer = dayjs(this.item.timer).format("YYYY-MM-DD HH:mm:ss");
      data.walls_id = this.item.id;
      // 我们要对pic_walls这个数组字段拼接成字符串(要判断是否有这个字段)
      if (this.item.pic_walls) {
        this.item.pic_walls.forEach((item, i) => {
          // 通过三个下划线分隔 如果第一张不需要用下划线分隔
          if (i === 0) {
            data.pic_walls += item;
          } else {
            data.pic_walls += "___" + item;
          }
        });
      }
      // 将解构的值存放到数组中
      Object.assign(data, {
        nickname,
        user_pic,
        from,
        message,
        uuId,
        cha_types,
        def_type,
        like_count,
      });
      let result = await this.$API.joinlikeByid(data);
      if (result.code === 200) {
        return this.$message({
          type: "success",
          message: result.message,
        });
      } else {
        return this.$message({
          message: result.message,
        });
      }
    },
  },
  computed: {
    // 截取评论字数限制
    msg() {
      if (this.message.length >= 30) {
        // 截取前30位
        this.message = this.message.slice(0, 30);
      }
      return this.message.length;
    },
    // 截取回复字数限制
    replymsg() {
      if (this.replymessage.length >= 30) {
        // 截取前30位
        this.replymessage = this.replymessage.slice(0, 30);
      }
      return this.replymessage.length;
    },
    // vuex中的个人信息
    userinfo() {
      return this.$store.state.user.userinfo;
    },
    // 解决mysql返回值带z带t问题
    timer() {
      return (timer) => {
        return dayjs(timer).format("YYYY-MM-DD HH:mm:ss");
      };
    },
  },
  components: {
    Report,
  },
};
</script>

<style lang="less" scoped>
.footer {
  display: flex;
  justify-content: space-between;
  width: 650px;
  .footer-item {
    a {
      cursor: pointer;
      color: #121121;
      font-size: 14px;
      i {
        font-size: 14px;
      }
    }
  }
  .footer-item:hover a {
    color: #008c8c;
  }
}
// 展开评论
.unflod {
  margin-top: 10px;
  width: 100%;
  height: auto;
  opacity: 0.8;
  border-radius: 10px;
  background: rgb(245, 241, 241);

  .line {
    margin: 0 auto;
    width: 95%;
    border-bottom: 1px solid #008c8c;
  }
  .sort {
    height: 20px;
    line-height: 20px;
    padding: 10px 0;
    display: flex;
    justify-content: start;
    .sort-item {
      font-weight: 500;
      color: #121121;
      margin: 0 20px;
      cursor: pointer;
    }
    .sort-item:hover {
      color: #008c8c;
    }
    .active {
      font-weight: 700;
      color: #008c8c;
    }
  }
  .content {
    height: auto;
    .content-item {
      padding: 10px 20px;
      box-sizing: border-box;
      display: flex;
      justify-content: start;
      .headimg {
        width: 35px;
        height: 35px;
        margin-right: 10px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      .headimg_div {
        width: 35px;
        height: 35px;
        margin-right: 10px;
        text-align: center;
        line-height: 35px;
        border-radius: 50%;
        background: #8590a6;
        font-size: 12px;
      }
      .nickname {
        font-size: 12px;
        h4 {
          color: #008c8c;
        }
        .message {
          color: #121121;
        }
        .click {
          margin-left: 20px;
          cursor: pointer;
          font-size: 12px;
          i {
            font-size: 12px;
          }
        }
        .click:hover {
          color: red;
        }
      }
      .reply_item {
        cursor: pointer;
      }
      .reply_item:hover {
        color: #008c8c;
      }
    }
  }
  .more {
    height: 20px;
    line-height: 20px;
    text-align: center;
    padding: 5px 10px;
    cursor: pointer;
  }
  .more:hover {
    color: #008c8c;
  }
  .hint {
    text-align: center;
    padding: 10px 0;
    width: 100%;
  }
}
.publish {
  text-align: center;
  padding: 15px 5px 5px;
  textarea {
    padding: 6px;
    border-radius: 5px;
    text-indent: 10px;
  }
  .publish-btn {
    display: flex;
    justify-content: end;
    padding: 0 5%;
    box-sizing: border-box;
    height: 35px;
    line-height: 35px;
    .btn {
      width: 65px;
      border-radius: 20px;
      background: #008c8c;
      text-align: center;
      font-size: 14px;
      font-weight: 700;
      color: #fff;
      border: none;
      cursor: pointer;
    }
    h5 {
      margin: 0 20px;
      .num {
        color: #008c8c;
      }
    }
  }
}
.dialog_title {
  padding-bottom: 10px;
  text-align: left;
  color: #008c8c;
  span {
    color: #121121;
  }
}
/deep/.el-dialog__body {
  padding-top: 0;
}
/deep/.el-dialog {
  min-width: 600px;
}
.comment_report {
  display: flex;
  justify-content: start;
  .headimg {
    margin-right: 10px;
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
  }
  .headimg_div {
    margin-right: 10px;
    background: #8590a6;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    line-height: 50px;
    text-align: center;
  }
}
</style>